package com.zw.demo01.utils;
import jdk.nashorn.internal.parser.JSONParser;
import lombok.extern.slf4j.Slf4j;


import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;

import java.lang.reflect.Array;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



/**
 * @ClassName: DataUtils
 * @Description TODO
 * @Author: zzw
 * @Date: 2023/3/28 14:50
 * @Version 1.0.0
 */
@Slf4j
public class DataUtils {

    private static final Pattern pattern = Pattern.compile("\\#\\{(.*?)\\}");
    private static Matcher matcher;

    /**
     * @MonthName： strRreplace
     * @Description： 字符串站位处理
     * @Param： [content, param]
     * @return： java.lang.String
     **/
    public static String strReplace(String content, Map<String, Object> param) throws JSONException {
        if (Objects.isNull(param)) {
            return null;
        }
        try {
            int i = 0;
            matcher = pattern.matcher(content);
            while (matcher.find()) {


                String key = matcher.group();
                String keyclone = key.substring(2, key.length() - 1).trim();
                boolean containsKey = param.containsKey(keyclone);

                if (containsKey && Objects.nonNull(param.get(keyclone))) {

                    String value = "'" + param.get(keyclone) + "'";
                    content = content.replace(key, value);
                }

                JSONArray jsonArray = new JSONArray(param.get("db").toString());
                if (i < jsonArray.length()) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i++);

                    if (jsonObject.get("id").equals(keyclone)) {
                        content = content.replace(key, jsonObject.get("name").toString());
                    }
                }
            }
            log.error("数据库语句：{}", content);

            return content;
        } catch (Exception e) {
            log.error("字符串站位处理：{}", e);
            return null;
        }

    }
}
